import axios from "axios"
import router from "@/router";
import store from '@/store'
import {getToken} from "@/utils/token-util";
import {updateExpireSession} from "@/store/mutations-types";

axios.defaults.timeout = 1000000;

async function onFulfilled(response) {
  if (response.status === 200) {
    switch (response.data.statusCode) {
      case 10200:
        return response.data;
      case 10302:
        if (response.data.data.startsWith("http")) {
          location.href = response.data.data.replace(/&amp;/g, '&');
          return response.data;
        }
        await router.replace(response.data.data);
        return response.data;
      case 10401:
        if (getToken() == null) {// 如果用户从未登陆过，直接跳转到登录地址，
          await router.replace("/login");
        } else { // 标记用户会话已过期
          store.commit(updateExpireSession, true);
        }
        break;
      case 10403:
        await router.replace("/403");
        return Promise.reject(response.data);
      case 10404:
        await router.replace("/404");
        return Promise.reject(response.data);
      case 10500:
        await router.replace("/500");
        return Promise.reject(response.data);
      default:
        break;
    }
  }
  return Promise.reject(response.data);
}

async function onRejected(error) {
  return Promise.reject(error);
}

const defaultInstance = axios.create({
  baseURL: process.env.VUE_APP_CONTEXT_PATH
});

defaultInstance.interceptors.request.use(config => {
  let token = getToken();
  if (token != null) {
    config.headers = {
      "token": token.token
    }
  }
  return config;
});
defaultInstance.interceptors.response.use(response => onFulfilled(response),
  error => onRejected(error));

export function defaultRequest(options) {
  return defaultInstance(options);
}

const staticInstance = axios.create({
  baseURL: "/"
});

export function staticRequest(options) {
  return staticInstance(options);

}
